﻿using System;

public class Triangle:Primitive
{
    public Vector3 A;
    public Vector3 B;
    public Vector3 C;
    public Vector3 N;
    public Triangle(Vector3 A, Vector3 B, Vector3 C, Vector3 N, LightIntensity ambient, LightIntensity diffuse, LightIntensity specular)
    {
        this.A = A;
        this.B = B;
        this.C = C;
        this.N = N;
        this.material = new Material(ambient, diffuse, specular);
    }
	public Triangle(Vector3 A, Vector3 B, Vector3 C, Vector3 N)
	{
        this.A = A;
        this.B = B;
        this.C = C;
        this.N = N;
        this.material = new Material();
	}
    public Triangle(Vector3 A, Vector3 B, Vector3 C)
    {
        this.A = A;
        this.B = B;
        this.C = C;
        Vector3 v1,v2,normal;
        v1 = new Vector3(A,B);
        v2 = new Vector3(A,C);
        normal = v1.cross(v2);
        normal.normalize();
        this.N = normal;
        this.material = new Material();
    }
    public override string ToString()
    {
        return "triangle{A" + A + ", B" + B + ", C" + C + ", N=" + N + "}";
    }
    public override Vector3 getNormal(Vector3 point)
    {
        N.normalize();
        return N;
    }
    public override Vector3 getCentre()
    {
        return A;
    }
    public override float getWidth()
    {
        return (A-B).length();
    }
    public override bool intersect(Ray r)
    {
        Plane trianglePlane = new Plane(this.A, this.N);
        if (trianglePlane.intersect(r))
        {
            Vector3 PA, PB, PC;
            Vector3 cross;
            PA = new Vector3(r.destination, this.A);
            PB = new Vector3(r.destination, this.B);
            PC = new Vector3(r.destination, this.C);
            cross = PA.cross(PB);
            if (cross.dot(this.N) < Triangle.minusZero)
            {
                r.distance = 0.0f;
                r.destination = new Vector3(r.origin + r.distance * r.direction);
                return false;
            }
            else
            {
                cross = PB.cross(PC);
                if (cross.dot(this.N) < Triangle.minusZero)
                {
                    r.distance = 0.0f;
                    r.destination = new Vector3(r.origin + r.distance * r.direction);
                    return false;
                }
                else
                {
                    cross = PC.cross(PA);
                    if (cross.dot(this.N) < Triangle.minusZero)
                    {
                        r.distance = 0.0f;
                        r.destination = new Vector3(r.origin + r.distance * r.direction);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
        }
        else
        {
            return false;
        }
    }
}
